public class AlternatePrintNumbers {
    private static final Object lock = new Object();
    private static int number = 1;
    private static final int MAX = 100;
    private static int currentThread = 1; // 1:线程1, 2:线程2, 3:线程3

    static class PrintTask implements Runnable {
        private final int threadId;

        public PrintTask(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    // 检查是否已经打印完所有数字
                    if (number > MAX) {
                        lock.notifyAll(); // 唤醒其他线程退出
                        break;
                    }

                    // 检查是否轮到自己打印
                    if (currentThread == threadId) {
                        System.out.println(Thread.currentThread().getName() + ": " + number);
                        number++;

                        // 更新下一个应该打印的线程
                        currentThread = currentThread % 3 + 1;

                        lock.notifyAll(); // 唤醒所有等待的线程
                    } else {
                        try {
                            lock.wait(); // 不是自己的轮次，等待
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintTask(1), "Thread-1");
        Thread t2 = new Thread(new PrintTask(2), "Thread-2");
        Thread t3 = new Thread(new PrintTask(3), "Thread-3");

        t1.start();
        t2.start();
        t3.start();
    }
}